<!--
 * @Author: Wang WeiHao
 * @Date: 2024-09-26 14:42:55
 * @LastEditors: Wang WeiHao
 * @LastEditTime: 2024-10-17 11:15:52
 * @Description: 
 * @FilePath: \geo-base-dm\src\views\main\ai-processing\right-popup.vue
-->
<template>
	<div v-show="popupShow" class="ai-popup">
		<!-- 解译任务提交框 -->
		<popupBox title="创建解译任务" @close="closePopup" />
		<div class="form-container">
			<el-form ref="formRef" label-position="top" label-width="100px" :model="aiTaskFormData">
				<el-form-item
					label="任务名称:"
					prop="taskName"
					:rules="[
						{
							required: true,
							message: '请填写任务名称',
							trigger: 'blur',
						},
					]"
				>
					<el-input v-model.trim="aiTaskFormData.taskName" />
				</el-form-item>
				<el-form-item label="待解译数据:">
					<div>{{ currentTiff }}</div>
				</el-form-item>
				<el-form-item
					label="解译类型"
					prop="type"
					:rules="[
						{
							required: true,
							message: '请选择解译类型',
							trigger: 'blur',
						},
					]"
				>
					<el-checkbox-group
						v-model="aiTaskFormData.type"
						class="type-group"
						@change="onTypesChange"
					>
						<el-checkbox
							v-for="(item, key) in base_config['vectorColor']"
							:key="key"
							:label="key"
							>{{ item.label }}</el-checkbox
						>
					</el-checkbox-group>
				</el-form-item>
				<!--				<el-form-item label="">-->
				<!--					<el-checkbox v-model="isSarWater">SAR水体</el-checkbox>-->
				<!--				</el-form-item>-->

				<el-form-item label="矢量范围:">
					<el-radio-group v-model="aiTaskFormData.region" @change="changeAreaType">
						<el-radio :label="3">全部范围</el-radio>
						<el-radio :label="6">绘制范围</el-radio>
						<el-radio :label="7">行政区划</el-radio>
						<el-radio :label="9">上传shp范围</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-upload
					v-show="aiTaskFormData.region == 9"
					v-model:file-list="uploadFile"
					v-loading="fileLoading"
					class="mb-9"
					drag
					:class="{ noneUpload: uploadFile.length > 0 }"
					action="//"
					:before-upload="beforeFileUpload"
					:on-remove="onRemoveFile"
					accept=".zip"
				>
					<div v-if="uploadFile.length === 0" class="flex flex-col items-center justify-center">
						<div><img src="@img/main/upload-icon.png" alt="" /></div>
						<div>
							<div>上传shp文件</div>
						</div>
					</div>
				</el-upload>
				<div v-show="aiTaskFormData.region == 7" style="display: flex; height: 50px">
					<div style="margin: 0 15px 0 15px">市/县</div>
					<el-select v-model="citycode" placeholder="请选择" style="width: 100px">
						<el-option
							v-for="item in cityOption"
							:key="item.ccode"
							:label="item.cname"
							:value="item.ccode"
						/>
					</el-select>
					<div style="margin: 0 15px 0 15px">区</div>
					<el-select v-model="qucode" placeholder="请选择" style="width: 100px">
						<el-option
							v-for="item in quOption"
							:key="item.dcode"
							:label="item.dname"
							:value="item.dcode"
						/>
					</el-select>
				</div>
				<div class="bottom-btn-group">
					<el-button class="elBtn" @click="createTask(formRef)"> 创建任务 </el-button>
					<el-button class="failBtn" @click="closePopup"> 取消 </el-button>
				</div>
			</el-form>
		</div>
	</div>
</template>

<script setup lang="ts">
import popupBox from "@cps/popupBox/index.vue";
import { useTaskStore } from "@/store";
import { addTask, shpGeo } from "@/api/ai-processing";
import mapTool from "@/utils/maptools/map";
import { ElMessage } from "element-plus";
import { getCitybycode, getqubycode } from "@/api/data-management/index";
import type { FormInstance } from "element-plus";
let base_config = BASE_CONFIG;
const formRef = ref<FormInstance>();
const taskStore = useTaskStore();
const popupShow = computed(() => taskStore.taskStatus);
const currentTiff = computed(() => taskStore.taskInfo?.fileName);
const currentArea = computed(() => taskStore.taskInfo?.geo);
// 解译任务创建弹窗 更新1
const aiTaskFormData: {
	type: string[];
	region: number;
	taskName: string;
} = reactive({
	type: [],
	region: 3,
	taskName: "",
});
watch(currentTiff, (newV) => {
	aiTaskFormData.taskName = newV || "";
});

const onTypesChange = (array: any) => {
	if (aiTaskFormData.type[aiTaskFormData.type.length - 1] === "sar_water") {
		aiTaskFormData.type = ["sar_water"];
	} else {
		let index = aiTaskFormData.type.findIndex((t) => t === "sar_water");
		if (index > -1) {
			aiTaskFormData.type.splice(index, 1);
		}
	}
};
const closePopup = () => {
	clearDraw();
	mapTool.clearVectorLayer("ai-interpretation");
	taskStore.setInfo({
		taskStatus: false,
		taskInfo: null,
	});
};
const isSarWater = ref(false);
// todo 创建解译任务
const createTask = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			aiTaskFormData.region === 3 ? changeAreaType(3) : "";
			console.log(aiTaskFormData);
			console.log(taskStore.taskInfo);
			// mapTool.
			// 创建解译任务请求参数
			if (taskStore.taskInfo !== null) {
				if (currentGeo.value) {
					// 这里根据aiTaskFormData.interpretType的值，来判断解译范围
					// interpretType: "build" | "water" | "forest" | "farmland" | "road",或者组合形式'build,water,forest'\
					// 情况一 taskType = 0 ,单类型解译
					// 情况二 taskType = 2 ,多类型解译
					let taskType = aiTaskFormData.type.length > 1 ? 2 : 0;
					let interpretType;
					if (aiTaskFormData.type.length > 1) {
						interpretType = aiTaskFormData.type.join(",");
					} else {
						interpretType = aiTaskFormData.type[0];
					}
					// 情况三 taskType = 4 ,sar水体解译
					if (isSarWater.value) {
						taskType = 5;
						interpretType = "water";
					}
					let aiParams = {
						preFileId: taskStore.taskInfo.id,
						preFilePath: taskStore.taskInfo.filePath,
						resolution: "1",
						interpretType,
						taskType,
						area: currentGeo.value,
						areaType: "useDefined",
						threshold: 45,
						taskName: aiTaskFormData.taskName,
					};
					let res = await addTask(aiParams);
					if (res.code === 200) {
						ElMessage({
							message: "创建解译任务成功",
							type: "success",
						});
						// 修改store状态，更新左侧list
						taskStore.setInfo({
							taskStatus: false,
							taskInfo: null,
						});
						// 如果当前还处于绘制状态，移除绘制交互
						if (currentFeature) {
							clearDraw();
						}
					}
				} else {
					alert("请先选择解译范围");
				}
			}
		}
	});
};
// todo 切换面积方式
const currentGeo: Ref<string | undefined> = ref();
// 已绘制的要素
let currentFeature: any;
const changeAreaType = (val: number) => {
	console.log(currentArea.value);

	switch (val) {
		case 3:
			console.log("全部范围");
			mapTool.locationByWkt("ai-interpretation", currentArea.value);
			currentGeo.value = currentArea.value;
			clearDraw();
			mapTool.clearVectorLayer("ai-interpretation");
			break;
		case 6:
			console.log("绘制范围");
			mapTool.clearVectorLayer("ai-interpretation");
			mapTool.addDrawInteraction("ai-interpretation", "Polygon", [
				{
					eventType: "drawstart",
					event: function () {
						if (currentFeature) {
							mapTool.vectorLayerList["ai-interpretation"]
								?.getSource()
								?.removeFeature(currentFeature);
						}
					},
				},
				{
					eventType: "drawend",
					event: function (evt: any) {
						currentFeature = evt.feature;
						currentGeo.value = mapTool.geometryToWkt(evt.feature.getGeometry());
					},
				},
			]);
			break;
		case 9:
			// todo 上传范围接入
			// alert("暂不支持，敬请期待");
			// aiTaskFormData.region = 3;
			clearDraw();
			break;
		default:
			break;
	}
};
const fileLoading = ref(false);
const uploadFile = ref([]);
const beforeFileUpload = async (file: File) => {
	let formData = new FormData();
	formData.append("file", file);
	fileLoading.value = true;
	const res = await shpGeo(formData);
	if (res.code === 200 && res.data.theGeom) {
		mapTool.clearVectorLayer("ai-interpretation");
		mapTool.locationByWkt("ai-interpretation", res.data.theGeom);
		mapTool.loadFeatureByWkt("ai-interpretation", res.data.theGeom, "", false, [
			"rgb(255,0,0)",
			"rgba(255, 0, 0, 0.5)",
		]);
		currentGeo.value = res.data.theGeom;
		fileLoading.value = false;
		return true;
	} else {
		ElMessage({
			message: "解析文件失败",
			type: "error",
		});
		fileLoading.value = false;
		return false;
	}
};
const onRemoveFile = () => {
	mapTool.clearVectorLayer("ai-interpretation");
	mapTool.locationByWkt("ai-interpretation", currentArea.value);
	currentGeo.value = "";
};
// 地图业务,清除画笔交互
const clearDraw = () => {
	mapTool.vectorLayerList["ai-interpretation"]?.getSource()?.removeFeature(currentFeature);
	mapTool.removeDrawInteraction("ai-interpretation");
};
const getcityOption = async () => {
	let res = await getCitybycode("420000");
	cityOption.value = res.data;
	console.log(res);
};
const cityOption = ref([]);
const quOption = ref([]);
const citycode = ref("");
const qucode = ref("");
const getquOption = async () => {
	let res = await getqubycode(citycode.value);
	quOption.value = res.data;
	console.log(res);
};
watch(citycode, (newV) => {
	qucode.value = "";
	getquOption();
});
const activeqcode = ref("");
watch(qucode, (newV) => {
	let item = quOption.value.find((item: any) => item.dcode === newV);
	let wkt = item?.edge;
	let qcode = item?.dcode;
	if (activeqcode.value) {
		// mapTool.removeFeatureById("ai-interpretation", "wkt" + activeqcode.value);
		mapTool.clearVectorLayer("ai-interpretation");
	}
	mapTool.loadFeatureByWkt("ai-interpretation", wkt, "wkt" + qcode, false, [
		"#1266E4",
		"#00000000",
	]);
	mapTool.locationByWkt("ai-interpretation", wkt);
	currentGeo.value = wkt;
	console.log(wkt);
	activeqcode.value = qcode;
});
onMounted(() => {
	getcityOption();
});
onBeforeUnmount(() => {
	mapTool.clearVectorLayer("ai-interpretation");
});
</script>

<style lang="scss" scoped>
/* 解译任务创建弹窗 */
.ai-popup {
	@apply fixed z-20;
	width: 348px;
	right: 20px;
	top: 176px;
	background: rgba(3, 18, 34, 0.9);
	border-radius: 4px;
}
.form-container {
	--el-text-color-regular: #fff;
	@apply px-3 py-6;
}
.type-group {
	@apply grid grid-cols-3;
	.el-checkbox {
		@apply w-1/3;
	}
}
.bottom-btn-group {
	@apply flex justify-between;
	> * {
		@apply w-1/2;
	}
}
.noneUpload {
	:deep().el-upload.is-drag {
		display: none !important;
	}
}
</style>
